import Apis from "./apis"
import Axios from "axios"
import Tools from "./tools"
require('es6-promise').polyfill()
import CONFIG from "./config"
import { reportError } from './handleError'
export default {
    common: CONFIG.ajax_common,
    new_common: CONFIG.new_common,
    auth() {
        const params = {
            full_url: window.location.href,
        }
        const route = Apis["auth"]; 
        Axios.get(`${this.common}/${route}`, { params }
        ).then( response => {
            const data = response.data
            if( data.code === 0 ){
                window.location.replace(data.body.auth_url)
            } else {
                alert(data.msg)
            }
        }).catch( error => {
            reportError(error)
        })
    },
    sid(cb) {
        const params = {
            code: Tools.getParams().code,
        }
        const route = Apis["sid"];
        Axios.get(`${this.common}/${route}`, { params }
        ).then( response => {
            const data = response.data
            if( data.code === 0 ){
                cb(data)
            } else {
                alert(data.msg)
            }
        }).catch( error => {
            reportError(error)
        })
    },
    sig(cb) {
        const params = {
            full_url: window.location.href,
        }
        const route = Apis["sig"];
        Axios.get(`${this.common}/${route}`, { params }
        ).then( response => {
            const data = response.data
            if( data.code === 0 ){
                cb(data)
            } else {
                alert(data.msg)
            }
        }).catch( error => {

        })
    },
    request(key, params, cb) {
        const route = Apis[key];
        const url = route.indexOf('wechat/') > -1 ? `${this.new_common}/${route}` : `${this.common}/${route}`;
        Axios.get(url, { params }
        ).then( response => {
            const data = response.data
            if( data.code === 0 ){
                cb(data)
            } else {
                alert(data.msg)
            }
        }).catch( error => {
            reportError(error)
        })
    },
    appendBaiduAnalysis() {
        var BAIDU_TONGJI_ID = CONFIG.baidu_id;
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?" + BAIDU_TONGJI_ID;
        var s = document.getElementsByTagName("script")[0]
        s.parentNode.insertBefore(hm, s)
    }
}